package com.me.EpicVN;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ViewFlipper;

import com.me.EpicVN.Data.NewsDetails;
import com.me.EpicVN.Utli.Constants;
import com.me.EpicVN.Utli.GlobalVariable;
import com.me.EpicVN.Utli.ShakeEventListener;
import com.me.EpicVN.Utli.htmlReader;
import com.me.EpicVN.Zoom.ImageZoomView;
import com.me.EpicVN.Zoom.TouchZoomListener;
import com.me.EpicVN.Zoom.ZoomControl;

public class ShowActivity extends Activity {
	
	private SensorManager mSensorManager;

	private ShakeEventListener mSensorListener;
    private ViewFlipper mViewFlipper;
    private int COUNT = 0;

    /** Image zoom view */
    private ImageZoomView mZoomView01;

    /** Zoom control */
    private ZoomControl mZoomControl01;

    /** Decoded bitmap image */

    /** On touch listener for zoom view */
    private TouchZoomListener mZoomListener01;

    private Animation leftIn, leftOut, rightIn, rightOut;
    private boolean isFling = false;
    ImageView img,imgLEFT,imgRIGHT;
    private Bitmap mBitmap;
    //private TextView txtTitle;
    static Context mContext;
    
    private Button btnBarMoi,btnBarBathu, btnBarAbout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.slide_show);
        mContext 	= this;
        btnBarMoi 	= (Button) findViewById(R.id.btnBarMoi);
        btnBarBathu = (Button) findViewById(R.id.btnBarBathu);
        imgLEFT 	= (ImageView) findViewById(R.id.LEFT);
        imgRIGHT	= (ImageView) findViewById(R.id.RIGHT);
        
        imgLEFT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				resetZoomState();
				// TODO Auto-generated method stub
				Log.w("hung", "COUNT = "+COUNT);
            	COUNT--;
        		if(COUNT < 0)
        		{
        			COUNT = GlobalVariable.listNews.size()-1;
        		}
        		Log.e("hung", "RIGHTT");
            	mBitmap = GlobalVariable.convertURLtoBitmap(GlobalVariable.listNews.get(COUNT).GetImgSrc());
            	//txtTitle.setText(GlobalVariable.listNews.get(COUNT).GetTitle());
            	mZoomView01.setImage(mBitmap);
            	
                mViewFlipper.setInAnimation(rightIn);
                mViewFlipper.setOutAnimation(rightOut);
                mViewFlipper.showPrevious();
                delayedAddView();
			}
		});
        
        imgRIGHT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				resetZoomState();
				// TODO Auto-generated method stub
				Log.w("hung", "COUNTLEFT = "+COUNT);
            	COUNT++;
            	Log.w("hung", " GlobalVariable.listNews.size() = "+ GlobalVariable.listNews.size());
            	if(COUNT == GlobalVariable.listNews.size())
            	{
            		COUNT = 0;
            	}
            	Log.w("hung", "hinh anh = "+GlobalVariable.listNews.get(COUNT).GetImgSrc());
            	mBitmap = GlobalVariable.convertURLtoBitmap(GlobalVariable.listNews.get(COUNT).GetImgSrc());
            	//txtTitle.setText(GlobalVariable.listNews.get(COUNT).GetTitle());
            	Log.e("hung", "LEFT");
            	mZoomView01.setImage(mBitmap);
                mViewFlipper.setInAnimation(leftIn);
                mViewFlipper.setOutAnimation(leftOut);
                mViewFlipper.showNext();
                delayedAddView();
			}
		});
        
        btnBarMoi.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				COUNT= 0;
				new syncTask().execute("http://epic.vn/moi");
			}
		});
        
        btnBarBathu.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				COUNT= 0;
				new syncTask().execute("http://epic.vn/bat-hu");
				
			}
		});
        try
        {
	        mBitmap 		= GlobalVariable.convertURLtoBitmap(GlobalVariable.listNews.get(COUNT).GetImgSrc());
	    	Log.d("SHOWACTIVITY", "src = "+GlobalVariable.listNews.get(COUNT).GetImgSrc());
	        //txtTitle 		= (TextView) findViewById(R.id.txtTitle1) ;
	        //txtTitle.setText(GlobalVariable.listNews.get(COUNT).GetTitle());
	        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
	        mSensorListener = new ShakeEventListener();   
	
	        mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
	
	          public void onShake() {
	        	  
	            COUNT++;
	        	if(COUNT == GlobalVariable.listNews.size())
	        	{
	        		COUNT = 0;
	        	}
	        	mBitmap = GlobalVariable.convertURLtoBitmap(GlobalVariable.listNews.get(COUNT).GetImgSrc());
	        	//txtTitle.setText(GlobalVariable.listNews.get(COUNT).GetTitle());
	        	Log.e("hung", "LEFT");
	        	mZoomView01.setImage(mBitmap);
	            mViewFlipper.setInAnimation(leftIn);
	            mViewFlipper.setOutAnimation(leftOut);
	            mViewFlipper.showNext();
	          }
	        });
	        
	        
	        
	        
	        Constants.SHOW_HIDE_NAVIGATION_BAR = true;
	        leftIn 			= AnimationUtils.loadAnimation(this, R.anim.push_left_in);
	        leftOut 		= AnimationUtils.loadAnimation(this, R.anim.push_left_out);
	        rightIn 		= AnimationUtils.loadAnimation(this, R.anim.push_right_in);
	        rightOut 		= AnimationUtils.loadAnimation(this, R.anim.push_right_out);
	
	        mViewFlipper 	= (ViewFlipper) findViewById(R.id.slide_show_view_flipper);
	
	        mZoomView01 = new ImageZoomView(getApplicationContext(), null);
	
	        mZoomControl01 = new ZoomControl();
	
	        mZoomListener01 = new TouchZoomListener(getApplicationContext());
	
	
	        mZoomListener01.setOnFlingListener(flingListener);
	
	        mZoomListener01.setZoomControl(mZoomControl01);
	
	        mZoomView01.setZoomState(mZoomControl01.getZoomState());
	
	        mZoomView01.setImage(mBitmap);
	        mZoomView01.setOnTouchListener(mZoomListener01);
	
	        mZoomControl01.setAspectQuotient(mZoomView01.getAspectQuotient());
	
	        resetZoomState();
	
	        mViewFlipper.addView(mZoomView01);
        }
        catch (Exception e) {
			// TODO: handle exception
		}
    }
    
    @Override
    protected void onResume() {
      super.onResume();
      try
      {
      mSensorManager.registerListener(mSensorListener,
          mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
          SensorManager.SENSOR_DELAY_UI);
      }
      catch (Exception e) {
		// TODO: handle exception
	}
    }

    @Override
    protected void onPause() {
    	try
    	{
      mSensorManager.unregisterListener(mSensorListener);
    	}
    	catch (Exception e) {
			// TODO: handle exception
		}
      super.onStop();
    }
    
    


    private final Handler handler = new Handler();

    private void delayedAddView() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                isFling = false;
            }
        }, 300);
    }

    private final TouchZoomListener.OnFlingListener flingListener = new TouchZoomListener.OnFlingListener() {
        @Override
        public void onFling(float velocityX) {
            if (isFling) {
                return;
            }
            isFling = true;
            resetZoomState();
            if (velocityX < 0) {
            	Log.w("hung", "COUNTLEFT = "+COUNT);
            	COUNT++;
            	Log.w("hung", " GlobalVariable.listNews.size() = "+ GlobalVariable.listNews.size());
            	if(COUNT == GlobalVariable.listNews.size())
            	{
            		COUNT = 0;
            	}
            	Log.w("hung", "hinh anh = "+GlobalVariable.listNews.get(COUNT).GetImgSrc());
            	mBitmap = GlobalVariable.convertURLtoBitmap(GlobalVariable.listNews.get(COUNT).GetImgSrc());
            	//txtTitle.setText(GlobalVariable.listNews.get(COUNT).GetTitle());
            	Log.e("hung", "LEFT");
            	mZoomView01.setImage(mBitmap);
                mViewFlipper.setInAnimation(leftIn);
                mViewFlipper.setOutAnimation(leftOut);
                mViewFlipper.showNext();
                
                
                
            } else {
            	Log.w("hung", "COUNT = "+COUNT);
            	COUNT--;
        		if(COUNT < 0)
        		{
        			COUNT = GlobalVariable.listNews.size()-1;
        		}
        		Log.e("hung", "RIGHTT");
            	mBitmap = GlobalVariable.convertURLtoBitmap(GlobalVariable.listNews.get(COUNT).GetImgSrc());
            	//txtTitle.setText(GlobalVariable.listNews.get(COUNT).GetTitle());
            	mZoomView01.setImage(mBitmap);
            	
                mViewFlipper.setInAnimation(rightIn);
                mViewFlipper.setOutAnimation(rightOut);
                mViewFlipper.showPrevious();
                
            }
            delayedAddView();
        }
    };

    

    /**
     * Reset zoom state and notify observers
     */
    private void resetZoomState() {
            mZoomControl01.getZoomState().setPanX(0.5f);
            mZoomControl01.getZoomState().setPanY(0.5f);
            mZoomControl01.getZoomState().setZoom(1f);
            mZoomControl01.getZoomState().notifyObservers();
            
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBitmap = null;
        mZoomView01.setOnTouchListener(null);
        mZoomControl01.getZoomState().deleteObservers();
        mZoomListener01.stopThread();
        GlobalVariable.listNews = null;

        System.gc();
    }
    
    public static class syncTask extends AsyncTask<String, Integer, Integer>
	{
		private ProgressDialog mProgressDialog;
		List<NewsDetails> l = new ArrayList<NewsDetails>();
		
		@Override
		protected void onPreExecute()
		{
			mProgressDialog = new ProgressDialog(mContext);
			//mProgressDialog.setCancelable(false);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.show();
		}
		
		

		@Override
		protected Integer doInBackground(String... params)
		{
					htmlReader hh;
					Log.w("hung", "vo day a moio ");
					try {
						hh = new htmlReader(new URL(params[0]));
						hh.getLinksByClass("col-1");
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
			
			for(int i = 0; i<GlobalVariable.listImage.size(); i++)
			{
				Log.d("ACTiVIty", "listImage = "+GlobalVariable.listImage.get(i));
				l.add(new NewsDetails(GlobalVariable.listImage.get(i), GlobalVariable.listTitle.get(i), null, null));
			}
            GlobalVariable.listNews = l;
            Log.e("HUNG", "size = "+GlobalVariable.listNews.size());
			return 0;
		}		
				
		@Override
		protected void onPostExecute(Integer result)
		{
			
			mProgressDialog.cancel();
			
			Intent refresh = new Intent(mContext, ShowActivity.class);
			mContext.startActivity(refresh);
			((Activity) mContext).overridePendingTransition(0, 0);
		
		}
	}
    
    @Override
	public boolean onKeyDown( int keyCode, KeyEvent event )
	{
		if ( keyCode == KeyEvent.KEYCODE_BACK )
		{
			// preventing default implementation previous to
			// android.os.Build.VERSION_CODES.ECLAIR
			return true;
		}

		return super.onKeyDown( keyCode, event );
	}
    
    @Override
	public boolean onKeyUp( int keyCode, KeyEvent event )
	{
		if ( keyCode == KeyEvent.KEYCODE_BACK )
		{
			showDialog(GlobalVariable.EXIT_APP);
			return true;
		}

		return super.onKeyUp( keyCode, event );
	}
    
    @Override
	protected Dialog onCreateDialog( int id )
	{
		switch ( id )
		{
			case GlobalVariable.EXIT_APP:
				return new AlertDialog.Builder(mContext).setTitle("Exit Epic.vn").setMessage("Do you really want to exit Epic.vn?").
					setPositiveButton("YES",
						new DialogInterface.OnClickListener()
						{
							public void onClick( DialogInterface dialog,
									int whichButton )
							{
								try
								{
									
									GlobalVariable.listImage = null;
									GlobalVariable.listNews = null;
									GlobalVariable.listUser = null;
									GlobalVariable.listTitle = null;
									GlobalVariable.listTimePost = null;
									
									System.runFinalizersOnExit( true );
									
									
								}
								catch ( Exception e )
								{
								}

								finish();
							}
						} ).setNegativeButton("NO",
						new DialogInterface.OnClickListener()
						{
							public void onClick( DialogInterface dialog,
									int whichButton )
							{
							}
						} ).create();
			default:
				return null;
		}
	}
    

    
}